package cn.zebra.dev.mall.module.orders.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.mall.module.orders.dto.SalesReturnDTO;
import cn.zebra.dev.mall.module.orders.vo.SalesReturnStateVO;
import cn.zebra.dev.mall.module.orders.vo.ShopSalesReturnStateVO;
import cn.zebra.dev.member.module.login.service.SecurityMemberService;
import cn.zebra.dev.member.module.member.entity.MemberEntity;
import cn.zebra.dev.member.module.member.service.MemberService;
import cn.zebra.dev.order.module.item.entity.OrdersItemEntity;
import cn.zebra.dev.order.module.item.service.OrdersItemService;
import cn.zebra.dev.other.module.orderssalesreturn.entity.OrdersSalesReturnEntity;
import cn.zebra.dev.other.module.orderssalesreturn.service.OrdersSalesReturnService;
import cn.zebra.dev.other.module.shopAfter.entity.ShopAfterEntity;
import cn.zebra.dev.other.module.shopAfter.service.ShopAfterService;
import cn.zebra.dev.shop.module.shop.entity.ShopEntity;
import cn.zebra.dev.shop.module.shop.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author feifeijunxin
 * @Date 2020/5/7 19:47
 * @Version 1.0
 */
@Api(tags = "订单退货")
@RestController
@RequestMapping("/orders/salesReturn")
public class SalesReturnController {

    @Autowired
    private OrdersSalesReturnService ordersSalesReturnService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private OrdersItemService ordersItemService;

    @Autowired
    private ShopAfterService shopAfterService;

    @Autowired
    private SecurityMemberService securityMemberService;


    @GetMapping("/userList")
    @ApiOperation("用户退货列表(可根据状态查询，如没有状态条件则默认查全部)")
    public Result<PageUtils<SalesReturnDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "userId") Long  userId,
            @RequestParam(value = "state",required = false) Long state){
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        map.put("userId",userId);
        map.put("state",state);
        PageUtils<OrdersSalesReturnEntity> pageUtils = ordersSalesReturnService.findPageByUserId(map);
        PageUtils<SalesReturnDTO> data = new PageUtils<>(pageUtils);
        List<OrdersSalesReturnEntity> list =pageUtils.getList();
        if(list.size() > 0){
            List<SalesReturnDTO> dtos = new ArrayList<>();
            List<Long> memberIds = list.stream().map(OrdersSalesReturnEntity::getUserId).collect(Collectors.toList());
            List<MemberEntity> memberEntities=memberService.findByIds(memberIds);
            List<Long> shopIds = list.stream().map(OrdersSalesReturnEntity::getShopId).collect(Collectors.toList());
            List<ShopEntity> shopEntities = shopService.findByIds(shopIds);
            List<Long> ordersItemIds = list.stream().map(OrdersSalesReturnEntity::getOrderItemId).collect(Collectors.toList());
            List<OrdersItemEntity> ordersItemEntities = ordersItemService.findByIds(ordersItemIds);
            list.forEach(entity ->{
                SalesReturnDTO dto = new SalesReturnDTO();
                BeanUtils.copyProperties(entity,dto);
                Optional<MemberEntity> memberEntityOptional = memberEntities.stream().filter(memberEntity -> memberEntity.getId().equals(entity.getUserId())).findAny();
                if(memberEntityOptional.isPresent()){
                    MemberEntity memberEntity = memberEntityOptional.get();
                    dto.setMemberName(memberEntity.getMemberName());
                }
                Optional<ShopEntity> shopEntityOptional = shopEntities.stream().filter(shopEntity -> shopEntity.getId().equals(entity.getShopId())).findAny();
                if(memberEntityOptional.isPresent()){
                    ShopEntity shopEntity = shopEntityOptional.get();
                    dto.setShopName(shopEntity.getShopName());

                }
                Optional<OrdersItemEntity> ordersItemsEntityOptional = ordersItemEntities.stream().filter(ordersItemEntity -> ordersItemEntity.getId().equals(entity.getOrderItemId())).findAny();
                if(ordersItemsEntityOptional.isPresent()){
                    OrdersItemEntity ordersItemEntity = ordersItemsEntityOptional.get();
                    dto.setProductAttributes(ordersItemEntity.getProductAttributes());
                    dto.setProductName(ordersItemEntity.getProductName());
                    dto.setProductImage(ordersItemEntity.getProductImage());
                }
                dtos.add(dto);
            });
            data.setList(dtos);
        }
        return Result.success(data);
    }


    @GetMapping("/shopList")
    @ApiOperation("店铺退货列表(可根据状态查询，如没有状态条件则默认查全部)")
    public Result<PageUtils<SalesReturnDTO>> shopList(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "shopId") Long  shopId,
            @RequestParam(value = "state",required = false) Long state){
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        map.put("shopId",shopId);
        map.put("state",state);
        PageUtils<OrdersSalesReturnEntity> pageUtils = ordersSalesReturnService.findPageByShopId(map);
        PageUtils<SalesReturnDTO> data = new PageUtils<>(pageUtils);
        List<OrdersSalesReturnEntity> list =pageUtils.getList();
        if(list.size() > 0){
            List<SalesReturnDTO> dtos = new ArrayList<>();
            List<Long> memberIds = list.stream().map(OrdersSalesReturnEntity::getUserId).collect(Collectors.toList());
            List<MemberEntity> memberEntities=memberService.findByIds(memberIds);
            List<Long> shopIds = list.stream().map(OrdersSalesReturnEntity::getShopId).collect(Collectors.toList());
            List<ShopEntity> shopEntities = shopService.findByIds(shopIds);
            List<Long> ordersItemIds = list.stream().map(OrdersSalesReturnEntity::getOrderItemId).collect(Collectors.toList());
            List<OrdersItemEntity> ordersItemEntities = ordersItemService.findByIds(ordersItemIds);
            list.forEach(entity ->{
                SalesReturnDTO dto = new SalesReturnDTO();
                BeanUtils.copyProperties(entity,dto);
                Optional<MemberEntity> memberEntityOptional = memberEntities.stream().filter(memberEntity -> memberEntity.getId().equals(entity.getUserId())).findAny();
                if(memberEntityOptional.isPresent()){
                    MemberEntity memberEntity = memberEntityOptional.get();
                    dto.setMemberName(memberEntity.getMemberName());
                }
                Optional<ShopEntity> shopEntityOptional = shopEntities.stream().filter(shopEntity -> shopEntity.getId().equals(entity.getShopId())).findAny();
                if(memberEntityOptional.isPresent()){
                    ShopEntity shopEntity = shopEntityOptional.get();
                    dto.setShopName(shopEntity.getShopName());

                }
                Optional<OrdersItemEntity> ordersItemsEntityOptional = ordersItemEntities.stream().filter(ordersItemEntity -> ordersItemEntity.getId().equals(entity.getOrderItemId())).findAny();
                if(ordersItemsEntityOptional.isPresent()){
                    OrdersItemEntity ordersItemEntity = ordersItemsEntityOptional.get();
                    dto.setProductAttributes(ordersItemEntity.getProductAttributes());
                    dto.setProductName(ordersItemEntity.getProductName());
                    dto.setProductImage(ordersItemEntity.getProductImage());
                }
                dtos.add(dto);
            });
            data.setList(dtos);
        }
        return Result.success(data);
    }


    @PostMapping("/save")
    @ApiOperation("客户退货")
    public Result save(@Valid @RequestBody SalesReturnStateVO vo) {
        OrdersSalesReturnEntity entity = new OrdersSalesReturnEntity();
        BeanUtils.copyProperties(vo,entity);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUserId(securityMemberService.getMemberId());
        ShopAfterEntity shopAfterEntity = shopAfterService.findById(entity.getShopAfterId());
        if(shopAfterEntity.getState() != 0L){
            return Result.error("商家还未同意处理，请耐心等待！！");
        }
        BeanUtils.copyProperties(shopAfterEntity,entity);
        entity.setState(1L);
        entity.setId(null);
        if(ordersSalesReturnService.save(entity)){
            return Result.success("操作成功！");
        }
        return Result.success("操作失败!");
    }

    @PostMapping("/update/{id}")
    @ApiOperation("商家确认退货！")
    public Result update(@PathVariable Long id,@Valid @RequestBody ShopSalesReturnStateVO vo) {
        OrdersSalesReturnEntity entity = new OrdersSalesReturnEntity();
        BeanUtils.copyProperties(vo,entity);
        if(!ordersSalesReturnService.update(entity,"id={0}",id)){
            return Result.success("确认退货失败!");
        }
//        entity = ordersSalesReturnService.findById(id);
//        OrdersItemEntity ordersItemEntitye = ordersItemService.findById(entity.getOrderItemId());
//        ShopEntity shopEntity = shopService.findById(entity.getShopId());
//        MemberEntity memberEntity = memberService.findById(entity.getUserId());
        //todo 退款
        return Result.success("确认退货成功!");
    }


}
